package tptecnicas.configuration;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.lang.String;

import javax.xml.stream.XMLStreamException;

import tptecnicas.util.Consts;

/*
 * ConfigProvider se encarga de realizar la inicializacion automatica de la configuracion
 * para luego devolver una instancia de Configuration.
 */

public class ConfigProvider {
	
	private Configuration configuration;
	
	public ConfigProvider() {
		loadConfiguration();
	}
	
	private void loadConfiguration() {
		if (fileExists(Consts.PROPERTIES_PATH)) {
			FileInputStream is = getInputStream(Consts.PROPERTIES_PATH);
			PropertiesReader reader = new PropertiesReader();
			configuration = reader.readFromProperties(is);
		} else if (fileExists(Consts.XML_PATH)){
			FileInputStream is = getInputStream(Consts.XML_PATH);
			XmlReader reader = new XmlReader();
			try {
				configuration = reader.readFromXML(is);
			} catch (XMLStreamException e) {
				System.err.println("Caught XMLStreamException: " + e.getMessage());
			}
		} else {
			PropertiesReader reader = new PropertiesReader();
			configuration = reader.readFromDefaultProperties();
		}
		
	}
	
	private boolean fileExists(String path) {
		return new File(path).exists();
	}
	
	private FileInputStream getInputStream(String path) {
		FileInputStream inputStream = null;
		try {
			inputStream = new FileInputStream(path);
		} catch (FileNotFoundException e) {
			System.err.println("File" + path + "not found");
		}
		return inputStream;
	}
	
	public Configuration getConfiguration() {
		return configuration;
	}
	
}